package com.vogue.supplymall.common.domain.validate;

import com.vogue.supplymall.common.domain.tool.MessageSourceUtils;
import com.vogue.supplymall.common.exception.AttributesNotNullableException;
import com.vogue.supplymall.common.exception.FormatIncorrectException;
import org.springframework.beans.factory.annotation.Autowired;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.io.Serializable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * The type Decimals validator.
 * 验证正整数
 *
 * @aouthor: zhangliang
 * @date: Create in 2017-12-15
 */
public class DecimalsValidator implements ConstraintValidator<Decimals, String>, Serializable {

    @Autowired
    protected MessageSourceUtils messageSourceUtils;
    private String attrName = "name";

    @Override
    public void initialize(Decimals constraintAnnotation) {
        attrName = messageSourceUtils.getMessage(com.vogue.supplymall.common.constant.ConstantBean.GLOBAL_SYSTEM
                + constraintAnnotation.name(), null);
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (value == null) {
            return true;
        }
        return isNumber(value);
    }

    private boolean isNumber(String str) {
        // 判断小数点后2位的数字的正则表达式
        Pattern pattern = Pattern.compile("^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?$");
        Matcher match = pattern.matcher(str);
        if (match.matches() == false) {
            throw new FormatIncorrectException(attrName);
        }
        return true;
    }
}
